package com.yisu.auction.api.web.controller;

import com.alibaba.fastjson.JSON;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Webhooks;
import com.yisu.auction.api.core.service.IMobileRechargeService;
import com.yisu.auction.api.core.service.IPrizeService;
import com.yisu.auction.api.core.service.IRechargeService;
import com.yisu.auction.api.core.service.impl.func.MobileChargeUtil;
import com.yisu.auction.api.domain.config.SystemConfig;
import com.yisu.auction.api.domain.request.rechargePackage.RechargeRequest;
import com.yisu.auction.api.domain.vo.mobileChargePackageVos.RechargeCallBackResponse;
import com.yisu.auction.api.domain.vo.mobileChargePackageVos.RechargeResponse;
import com.yisu.auction.api.domain.vo.pingXX.PingXXRequestObjectVo;
import com.yisu.auction.ewf.common.utils.HTTPClientUtil;
import com.yisu.auction.ewf.common.web.JsonResult;
import com.yisu.auction.ewf.entity.MobileRecharge;
import com.yisu.auction.ewf.entity.Recharge;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * author: 赵杰
 * Business Description：支付回调
 * createTime：2017/8/21
 */
@Controller
@RequestMapping("/notify")
public class NotifyController extends MobileChargeUtil {

    @Resource
    private IRechargeService iRechargeService;
    @Resource
    private IMobileRechargeService iMobileRechargeService;
    @Resource
    private IPrizeService iPrizeService;
    @Resource
    private MobileChargeUtil mobileChargeUtil;

    @Resource
    private SystemConfig systemConfig;


    /**
     * ping++返回相应实体
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/MobileChargeNotify", produces = "application/json; charset=utf-8")
    @ResponseBody
    public String MobileChargeNotify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF8");
        //获取头部所有信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            System.out.println(key + " " + value);
        }
        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        if (!StringUtils.isEmpty(buffer)) {
            RechargeCallBackResponse rechargeResponse = JSON.parseObject(buffer.toString(), RechargeCallBackResponse.class);
            if (rechargeResponse == null)
                return "false";
            if (rechargeResponse.getState().equals("3")) {
                if (iMobileRechargeService.notify(rechargeResponse)) {
                    return "true";
                } else {
                    return "false";
                }
            }
        }
        return "false";
    }


    /**
     * ping++返回相应实体
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/PingNotifyTest", produces = "application/json; charset=utf-8")
    @ResponseBody
    public void PingNotifyTest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RechargeRequest rechargeRequest = new RechargeRequest();
        rechargeRequest.setOrderId("null20170912113833255");
        if (iRechargeService.notifyResult(rechargeRequest)) {
            return;
        }
    }

    /**
     * ping++返回相应实体
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping(value = "/PingNotify", produces = "application/json; charset=utf-8")
    @ResponseBody
    public void PingNotify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF8");
        //获取头部所有信息
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            System.out.println(key + " " + value);
        }
        // 获得 http body 内容
        BufferedReader reader = request.getReader();
        StringBuffer buffer = new StringBuffer();
        String string;
        while ((string = reader.readLine()) != null) {
            buffer.append(string);
        }
        reader.close();
        // 解析异步通知数据
        Event event = Webhooks.eventParse(buffer.toString());
        if ("charge.succeeded".equals(event.getType())) {
            PingXXRequestObjectVo pingXXRequestObjectVo = JSON.parseObject(event.getData().getObject().toString(), PingXXRequestObjectVo.class);
            //处理股票配资项目回调
            if (pingXXRequestObjectVo.getOrder_no().toUpperCase().contains("STOCK")) {
                //以下处理商城订单逻辑
                Map<String, String> param = new HashMap<>();
                param.put("orderId", pingXXRequestObjectVo.getOrder_no());
                String json = HTTPClientUtil.doPost(systemConfig.getStockPayNotifyUrl(), param);
                JsonResult jsonResult = JSON.parseObject(json, JsonResult.class);
                if (jsonResult.getErrorCode() == 0) {
                    response.setStatus(200);
                } else {
                    response.setStatus(500);
                }
            } else {
                RechargeRequest rechargeRequest = new RechargeRequest();
                rechargeRequest.setOrderId(pingXXRequestObjectVo.getOrder_no());
                Recharge recharge = iRechargeService.getRechargeOrderByOrderId(rechargeRequest.getOrderId());
                if (recharge == null) {
                    response.setStatus(500);
                } else {
                    if (recharge.getOrderNo().toUpperCase().contains(MobileRecharge.RechargeTypeEnum.Balance.name)
                            || recharge.getOrderNo().toUpperCase().contains(MobileRecharge.RechargeTypeEnum.Traffic.name)) {
                        //走话费流量充值业务
                        if (iRechargeService.notifyResult(rechargeRequest)) {
                            mobileChargeUtil.FlowRecharge(recharge.getOrderNo());
                            response.setStatus(200);
                        } else {
                            response.setStatus(500);
                        }
                    } else {
                        if (iRechargeService.notifyResult(rechargeRequest))
                            response.setStatus(200);
                        else {
                            response.setStatus(500);
                        }
                    }
                }
            }

        } else if ("refund.succeeded".equals(event.getType())) {
            response.setStatus(200);
        } else {
            response.setStatus(500);
        }
    }

}
